/**
 * 个人中心
 */
var userCenterController={
    picId:null,
    init:function(){
        $("#saveUser").click(function(){
            userCenterController.saveUser();
        });
    },
    saveUser:function(){
        var form_data = {
            id:$("#userId").val(),
            username:$("#username").val(),
            realname:$("#realname").val(),
            sex:$('input:radio:checked').val(),
            email:$("#email").val(),
            address:$("#address").val(),
            picId:userCenterController.picId
        };
        $.ajax({
            type: "post",
            url: "/custom/usercenter/saveuserinfo",
//                cache:false,
//                async:false,
            data:form_data,
            success: function (data) {
                if(data == 2){
                    alert("修改成功");
                }
            },
            failure: function (result) {
                alert('获取失败');
            }
        });
    }
};
var updatePasswordController = {
    init:function(){
        updatePasswordController.setListeners();
        updatePasswordController.validatorMethod();
    },
    clickRegister:function(){
        var oldPassword = $("#updateForm #oldPassword").val();
        var newPassword = $("#updateForm #newPassword").val();
        if(oldPassword && newPassword){
            $.ajax({
                type: "post",
                url: "/custom/usercenter/updatepassword",
//                cache:false,
//                async:false,
                dataType: "json",
                data:{
                    password:newPassword,
                },
                success: function(data){
                    if(data == 2){
                        alert("修改成功");
                    }else if(data == 1){
                        // window.location.href="/custom/product/page/list";
                    }
                },
                failure:function (result) {
                    alert('修改失败');
                }
            });
        }else{
            alert("请输入密码");
        }
    },
    setListeners:function(){
        $( "#updateForm" ).validate( {
            submitHandler : function(form) {
                updatePasswordController.clickRegister();
            },
            rules: {
                oldPassword: {
                    required:true,
                    checkPasswordIsExists:true
                },
                newPassword: {
                    required:true,
                    checkPasswordIsDiff:true
                },
                confirmPassword: {
                    required: true,
                    // minlength: 5,
                    equalTo: "#newPassword"
                },
            },
            messages: {
                oldPassword: {
                    required: "请输入原密码",
                    checkPasswordIsExists:"原密码不正确"
                },
                newPassword: {
                    required: "请输入新密码",
                    checkPasswordIsDiff:"新密码和原密码不能相同"
                },
                confirmPassword: {
                    required: "请输入确认密码",
                    // minlength: "Your password must be at least 5 characters long",
                    equalTo: "请输入相同的确认密码"
                },
            },
            //errorElement: "em",
            errorPlacement: function ( error, element ) {
                // Add the `help-block` class to the error element
                error.addClass( "help-block" );

                if ( element.prop( "type" ) === "checkbox" ) {
                    error.insertAfter( element.parent( "label" ) );
                } else {
                    error.insertAfter( element.parent() );
                }
            },
            highlight: function ( element, errorClass, validClass ) {
                $( element ).parent().next().addClass( "has-error" ).removeClass( "has-success" );
            },
            unhighlight: function (element, errorClass, validClass) {
                $( element ).parent().next().addClass( "has-success" ).removeClass( "has-error" );
            }
        } );
    },
    validatorMethod:function(){
        $.validator.addMethod("checkPasswordIsExists", function(value, element) {
            var flag;
            var password = $("#updateForm #oldPassword").val();
            $.ajax({
                "dataType" : 'text',
                "type" : "POST",
                "async" : false,
                "url" : "/custom/usercenter/checkpassword",
                "data" : {
                    password : password
                },
                "success" : function(data) {
                    if(data == 1) {
                        flag = false;
                    } else {
                        flag = true;
                    }
                }
            }).responseText;
            return this.optional(element) || flag == true;
        }, "原密码不正确");

        $.validator.addMethod("checkPasswordIsDiff", function(value, element) {
            var flag;
            var password = $("#updateForm #oldPassword").val();
            var newPassword = $("#updateForm #newPassword").val();
            if(password == newPassword) {
                flag = false;
            } else {
                flag = true;
            }
            return this.optional(element) || flag == true;
        }, "新密码和原密码不能相同");
    },
};
var serverController = {
    init:function(){
        serverController.fillTable();
    },
    fillTable:function(){
        $.get("/custom/usercenter/server",function(data,status){
            var html_ = "";
            $.each(data.rows,function(index,item){
                var status = "正常";
                var colour = "text-success";
                if(item.status == 1) {
                    status = "运行中";
                } else if(item.status == 2) {
                    status = "异常";
                    colour = "text-warning";
                }
                html_ += "<tr><th>"+item.name+"（"+item.ip+"）</th><td class="+colour+">"+status+"</td><td style='cursor: pointer'><a data-toggle='modal' data-target='#detail'>详情</a></td></tr>"
            });
            $("#servers").html(html_);
        })
    }
};

var messagesController = {
    init:function(){
        messagesController.initPage();
        messagesController.initButton();
    },
    initPage:function(){
        $.get("/custom/usercenter/data/size",function(data,status){
            var pageCount = Math.ceil(data/pageRows);
            $('.M-box4').pagination({
                isHide:true,
                coping:true,//是否开启首页和末页，值为boolean
                homePage:'首页',
                endPage:'末页',
                prevContent:'上页',
                nextContent:'下页',
                count:1,//当前选中页前后页数
                pageCount: pageCount,//总页数
                jump: true,//是否开启跳转到指定页数，值为boolean类型
                callback:function(api){
                    messagesController.buildData(api);
                }
            },function(api){
                messagesController.buildData(api);
            });
        });
    },
    buildData:function(api){
        var data = {
            page:api.getCurrent(),
            rows:pageRows
        };
        $.ajax({
            type: "post",
            url: "/custom/usercenter/data/list",
//                cache:false,
//                async:false,
            dataType: "json",
            data:data,
            success: function(json){
                var pageCount = Math.ceil(json.totalData/10);
                api.setPageCount(pageCount);
                $("#messages").html("");
                if(json.rows.length>0){
                    $(".M-box4").show();
                    $("#nodatatip").hide();
                    messagesController.showHtmlData(json.rows);
                }
                // else{
                //     $(".M-box4").hide();
                //     $("#nodatatip").show();
                // }
            },
            failure:function (result) {
                console.log("加载信息失败");
            }
        });
    },
    initButton:function(){
        $("#read").click(function(){
            var ids = {};
            var check = $("#messages input[type='checkbox']");
            var index = 0;
            $.each(check, function(i,n){
                if(n.checked) {
                    if (n.value && ''!= n.value) {
                        ids[index] = Number(n.value);
                        index++;
                    }
                }
            });
            if(JSON.stringify(ids) == "{}") {
                alert("请选择一条记录！");
                return;
            } else {
                var data = {
                    ids:ids
                };
                $.ajax({
                    type: "post",
                    url: "/custom/usercenter/messages/read",
                    data:data,
                    success: function(result){
                        alert("修改成功");
                        messagesController.initPage();
                        $("#selectAll")[0].checked = false;
                    },
                    failure:function (result) {
                        console.log("提交失败");
                    }
                });
            }
        });
        $("#delete").click(function(){
            var ids = {};
            var check = $("#messages input[type='checkbox']");
            var index = 0;
            $.each(check, function(i,n){
                if(n.checked) {
                    if (n.value && ''!= n.value) {
                        ids[index] = Number(n.value);
                        index++;
                    }
                }
            });
            if(JSON.stringify(ids) == "{}") {
                alert("请选择一条记录！");
                return;
            } else {
                var data = {
                    ids:ids
                };
                console.log(data)
                $.ajax({
                    type: "post",
                    url: "/custom/usercenter/messages/delete",
                    data:data,
                    success: function(result){
                        alert("删除成功");
                        messagesController.initPage();
                        $("#selectAll")[0].checked = false;
                    },
                    failure:function (result) {
                        console.log("提交失败");
                    }
                });
            }
        });
        $("#selectAll").click(function(){
            var check = $("#messages input[type='checkbox']");
            if($("#selectAll")[0].checked){
                $.each(check, function(i,n) {
                    n.checked = true;
                });
            } else {
                $.each(check, function(i,n) {
                    n.checked = false;
                });
            }
        });
        $("#clear").click(function(){
            var check = $("#messages input[type='checkbox']");
            $.each(check, function(i,n) {n.checked = false;});
            $("#selectAll")[0].checked = false;
        });
    },
    showHtmlData:function(data){
        $.each(data, function(i,n){
            var weight = 0;
            if(n.status == 0) {
                weight = 900;
            }
            var htmldata = '<tr>'
                +' <th style="text-align: center;"><input type="checkbox" value='+ n.id+'></th>'
                +' <td style="text-align: left;font-weight: '+weight+';cursor: pointer;width: 500px;word-break:break-all;" onclick="messagesController.rowRead('+ n.id+')">'+ n.content+'</td>'
                +' <td>'+ messagesController.dateFormater(n.createTime)+'</td>'
                +' /tr>';
            $("#messages").append(htmldata);
        });
    },
    dateFormater: function (value) {
        if(value) {
            return (new Date(value)).format("yyyy-MM-dd");
        } else {
            return '';
        }
    },
    rowRead: function(id){
        var ids = {};
        if(id) {
            ids[0] = id;
            var data = {
                ids:ids
            };
            $.ajax({
                type: "post",
                url: "/custom/usercenter/messages/read",
                data:data,
                success: function(result){
                    messagesController.initPage();
                },
                failure:function (result) {
                }
            });
        }
    }
};

$(function(){
    userCenterController.init();
    updatePasswordController.init();
    serverController.init();
    messagesController.init();
    if ($("#sexValue").val() == "true") {
        $("#sex1").attr("checked",true);
        $("#sex2").attr("checked",false);
    } else {
        $("#sex1").attr("checked",false);
        $("#sex2").attr("checked",true);
    }

    var type = getQueryString("type");
    console.log(type);
    if(type){
       $("#usercentertab a[href='#"+type+"']").tab('show');
    }
});

function uploadhead(data){
    var file = document.getElementById("previewImg").files[0];
    var formData = new FormData();
    formData.append("file", file);
    $.ajax({
        type : "POST",
        cache: false,
        url : "/fileUpload/webupload",
        data : formData,
        processData:false,
        contentType:false,
        success : function(data) {
            userCenterController.picId = data.id;
            document.getElementById("imghead").src ='/fileDownLoad/showFile/'+data.id;
            document.getElementById("imghead2").src ='/fileDownLoad/showFile/'+data.id;
        }
    })
}